<template>
	<u-sticky>
		<view class="tab-wrap">
			<scroll-view scroll-x="true" style="height: 120rpx;white-space: nowrap;">
				<view class="tab-list">
					<view :class="['tab-item', tabCurrent == i ? 'active' : '']" v-for="(item, i) in tabList" :key="item.id" @tap="tabCurrentChange(i)">
						{{item.name}}
					</view>
				</view>
			</scroll-view>
		</view>
	</u-sticky>

	<view class="container">
		<!-- 九宫格 -->
		<view class="grid-wrap">
			<u-grid :border="false" col="3">
				<u-grid-item v-for="(item, i) in productList" :key="i" @click="goStoreDetail($event, item.id)">
					<view class="commodity-item grid-bottom">
						<view class="img-box">
							<u-image width="220rpx" height="200rpx" :src="checkAndFixUrl(item.cover)" mode="aspectFit"></u-image>
						</view>
						<view class="content-box">
							<view class="title">{{ item.name }}</view>
							<view class="price-box">
								<view class="price">￥{{ item.price }}</view>
								<view class="icon-box" @tap.stop="showPop($event,item)">
									<u-image width="44rpx" height="44rpx" :src="getServerStatic('/static/images/a63.png')" ></u-image>
								</view>
							</view>
						</view>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
	</view>

	<!-- 选择规格弹窗 -->
    <SelectSku ref="selectSkuRef"
               :productAttrs="productAttrs"
               :productSkus="productSkus"
               :productInfo="productInfo"
               @confirmSku="confirmSku"
    >
    </SelectSku>

    <u-loadmore :status="loadMoreStatus" />
</template>

<script setup>
    import {ref, reactive, readonly} from "vue"
    import {onLoad, onShow, onReachBottom} from '@dcloudio/uni-app'
    import {getCategory, getProductDetail, getProductList} from "@/api/product";
    import {checkAndFixUrl, getServerStatic} from "@/utils/tool";
    import SelectSku from '@/components/SelectSku'
    import {storeCart} from "@/api/cart";
    const selectSkuRef = ref(null)

    const loadMoreStatus = ref('loadmore')

    const currentPage = ref(1)
    const perPage = ref(10)

    // 分类ID
    const categoryId = ref(0)

    // 搜索参数
    const keyword = ref('')

	onLoad((evt) => {
        console.log('商品列表参数', evt)

        categoryId.value = evt?.category_id ?? 0
        keyword.value = evt?.keyword ?? ''

        handleGetCategory()

        handleGetProductList()
		// uni.setNavigationBarTitle({
		// 	'title': '商品'
		// })
	})

    onReachBottom(() => {
        handleGetProductList()
        console.log("上拉加载更多")
    })

    // 二级分类
	const tabCurrent = ref(0)
	const tabList = ref([
		{name: '全部', id: 0},
	])

    // 切换分类
	const tabCurrentChange = e => {
		console.log('切换分类', tabList.value[e].id);
        tabCurrent.value = e
        categoryId.value = tabList.value[e].id
        refreshPage()
        handleGetProductList()
	}

    // 获取分类
    const handleGetCategory = async () => {
        const {code, data} = await getCategory({parent_id: categoryId.value})
        if (code == 1) {
            tabList.value = data
            // 一级
            if (categoryId.value) {
                tabList.value.splice(0, 0, {name: '全部', id: categoryId.value})
            } else {
                tabList.value.splice(0, 0, {name: '全部', id: 0})
            }
        }
        console.log(data)
    }

    // 商品列表
    const productList = ref([])
    const refreshPage = () => {
        currentPage.value = 1
        productList.value = []
    }

    const getSearchParams = () => {
        return {
            category_id: categoryId.value ?? 0,
            currentPage: currentPage.value ?? 1,
            perPage: perPage.value,
            keyword: keyword.value ?? '',
        }
    }
    const handleGetProductList = async () => {

        const param = getSearchParams()

        const {code ,data} = await getProductList(param)
        if (code == 1) {
            if (data.length <= 0) {
                loadMoreStatus.value = 'nomore'
                console.log('noting')
            } else {
                currentPage.value++
                // 数量少于每页数量
                if (data.length < perPage.value) {
                    loadMoreStatus.value = 'nomore'
                } else {
                    loadMoreStatus.value = 'loadmore'
                }
            }
            productList.value = productList.value.concat(data)
        } else {
            loadMoreStatus.value = 'nomore'
        }
        console.log(data)
    }


    // 商品属性
    const productAttrs = ref([])
    // 商品规格
    const productSkus = ref([])
    // 商品信息
    const productInfo = ref([])

    // 展示规格
    const showPop = async (event,item) => {
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await getProductDetail({product_id: item.id})
        uni.hideLoading();

        if (code == 1) {
            productInfo.value = data?.product ?? {}
            productAttrs.value = data?.product?.attrs ?? []
            productSkus.value = data?.product?.skus ?? []
            console.log('商品属性',productAttrs.value)
            console.log('商品SKU',productSkus.value)
            selectSkuRef.value.open()

        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
    }

    // 确认sku 加入购物车
    const confirmSku = async (result) => {
        console.log(result)
        console.log('选择的sku', result.sku.attr_name)
        // 加入购物车
        uni.showLoading({
            title: '加载中'
        });
        const {code, data, message} = await storeCart({sku_id: result.sku.id, quantity: result.quantity })
        uni.hideLoading();
        if (code === 1) {
            uni.showToast({
                mask: true,
                title: '已添加',
                icon: 'success'
            })
        } else {
            uni.showModal({
                title: '提示',
                content: message ?? "请求异常",
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
    }


	// 商品详情
	const goStoreDetail = (e, productId) => {
        if (productId) {
            uni.navigateTo({
                url: `/mine/drug-store/detail?product_id=${productId}`
            })
        }
	}
</script>

<style lang="scss" scoped>
	.tab-wrap {
		width: 100%;
		height: 120rpx;
		background-color: #fff;
		.tab-list {
			height: 100%;
			display: flex;
			align-items: center;
			padding-left: 26rpx;
			.tab-item {
				color: #666666;
				font-size: 30rpx;
				padding: 15rpx 36rpx;
				background: #EEEEEE;
				border-radius: 36rpx;
				margin-right: 26rpx;
				border: 1rpx solid #EEEEEE;
			}
			.active {
				border: 1rpx solid #516DDB;
				background: #E5EAFF;
				color: #3B6CDF;
			}
		}
	}
	.grid-wrap {
		padding: 30rpx 26rpx;
		.grid-bottom {
			margin-bottom: 30rpx;
		}
		.commodity-item {
			position: relative;
			width: 220rpx;
			// height: 330rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			margin-right: 20rpx;
			overflow: hidden;
			box-shadow: 0rpx 0rpx 10rpx 1rpx rgba(102,102,102,0.16);
			z-index: 99;
			.content-box {
				padding: 8rpx 8rpx 15rpx;
				.title {
					color: #666666;
					@include over-ellip();
					margin-bottom: 12rpx;
				}
				.price-box {
					@include between(100%);
					.price {
						font-size: 28rpx;
						color: #F55726;
					}
					.icon-box {
						@include center(44rpx, 44rpx);
						background: #516DDB;
						border-radius: 50%;
					}
				}
			}
		}
	}
	.sku-pop {
		background: #FFFFFF;
		border-radius: 30rpx 30rpx 0rpx 0rpx;
		padding: 40rpx 40rpx 52rpx;
		.title {
			font-size: 32rpx;
			color: #222222;
			text-align: center;
			margin-bottom: 50rpx;
		}
		.content-box {
			@include between(100%, 100%);
			margin-bottom: 70rpx;
			.right {
				flex: 1;
				margin-left: 22rpx;
				@include between(100%, 170rpx);
				flex-direction: column;
				align-items: flex-start;
				// padding: 10rpx 0;
				color: #000000;
				font-size: 30rpx;
				.com-title {
					color: #F55726;
					font-size: 28rpx;
					.price {
						font-weight: bold;
						font-size: 50rpx;
					}
				}
			}
		}
		.sku-select-box {
			margin-bottom: 40rpx;
			.sku-tip {
				color: #333333;
				font-size: 30rpx;
				margin-bottom: 30rpx;
			}
			.sku-list {
				@include start();
				flex-wrap: wrap;
				.sku-item {
					padding: 20rpx 26rpx;
					background: #EBEBEB;
					border-radius: 20rpx;
					color: #333333;
					font-size: 30rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					border: 1rpx solid #EBEBEB;
				}
				.active {
					background: #E8EBF6;
					border: 1rpx solid #516DDB;
				}
			}
		}
		.pay-number {
			margin-top: 50rpx;
			@include between(100%);
		}
		.confirm-btn {
			margin-top: 60rpx;
		}
	}
</style>
